<!DOCTYPE html>
<html lang="en">
<head>
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
		<meta charset="utf-8" />
		<title>首页 - 树状图统计</title>
		<meta name="description" content="overview &amp; stats" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
		<!-- bootstrap & fontawesome -->
		<link rel="stylesheet" href="${rc.contextPath}/assets/css/bootstrap.min.css" />
		<link rel="stylesheet" href="${rc.contextPath}/assets/font-awesome/4.2.0/css/font-awesome.min.css" />
		<!-- page specific plugin styles -->
		<link rel="stylesheet" href="${rc.contextPath}/assets/css/jquery-ui.custom.min.css" />
		<link rel="stylesheet" href="${rc.contextPath}/assets/css/jquery.gritter.min.css" />
		<!-- text fonts -->
		<link rel="stylesheet" href="${rc.contextPath}/assets/fonts/fonts.googleapis.com.css" />
		<!-- BootstrapValidator -->
		<link rel="stylesheet" href="${rc.contextPath}/assets/css/bootstrapValidator.min.css" />
		<!-- ace styles -->
		<link rel="stylesheet" href="${rc.contextPath}/assets/css/ace.min.css" class="ace-main-stylesheet" id="main-ace-style" />
		<!-- ace settings handler -->
		<script src="${rc.contextPath}/assets/js/ace-extra.min.js"></script>
		<link rel="stylesheet" href="${rc.contextPath}/assets/css/bootstrap-datetimepicker.min.css" />
<style>
.node {
  cursor: pointer;
}
.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 1.5px;
}
.node rect {
  fill: red;
  stroke: red;
  stroke-width: 1.5px;
}
.node ellipse {
  fill: black;
  stroke: black;
  stroke-width: 1.5px;
}
.node text {
  font: 10px sans-serif;
}
.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 1.5px;
}
.dFilter
{
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 999;
    background-color:Gray;
    left: 0px;
    top: 0px;
}
.dBody
{
    position: absolute;
    z-index: 1000;
    border: 2px solid #C4D9F6;
    background-color: white;
}
.dHeader
{
    
    height: 20px;
    width: 100%;
    line-height: 20px;
}
.dHeaderEdit
{
    
    height: 50px;
    width: 100%;
    line-height: 20px;
}
.dHeaderDel
{
    
    height: 50px;
    width: 100%;
    line-height: 20px;
}
.dHeader label
{
    color: Black;
    float: left;
    font-weight: bold;
    margin-left: 5px;
    line-height:20px;
}
.dHeader img
{
    float: right;
    height:18px;
    width:18px;
    background-image: url(${rc.contextPath}/images/favicon.png);
}
</style>
</head>

<body class="no-skin" style="background-color: #FFF;">
		<div class="page-content">
			<div id="ti" class="page-header">
				<h1>
					树状图编辑
					<small>
						<i class="ace-icon fa fa-angle-double-right"></i>
						动态zengshan
					</small>
				</h1>
			</div>
			<div id="wsh" class="row">
				<div class="col-xs-12">
					<div id="treeShow" class="row">
					</div>
				</div>
			</div>
		</div>
<!-- basic scripts -->
		<script src="${rc.contextPath}/assets/js/jquery.2.1.1.min.js"></script>
		<script src="${rc.contextPath}/assets/js/bootstrap.min.js"></script>
		<script src="${rc.contextPath}/assets/js/jquery-ui.custom.min.js"></script>
		<script src="${rc.contextPath}/assets/js/jquery.ui.touch-punch.min.js"></script>
		<script src="${rc.contextPath}/assets/js/bootbox.min.js"></script>
		<script src="${rc.contextPath}/assets/js/jquery.gritter.min.js"></script>
		<script src="${rc.contextPath}/assets/js/spin.min.js"></script>
		<!-- ace scripts -->
		<script src="${rc.contextPath}/assets/js/ace-elements.min.js"></script>
		<script src="${rc.contextPath}/assets/js/ace.min.js"></script>
		<!-- validator scripts -->
		<script src="${rc.contextPath}/assets/js/bootstrapValidator.min.js"></script>
		<!-- user scripts -->
		<script src="${rc.contextPath}/assets/js/user/base.js"></script>
		<script src="${rc.contextPath}/assets/js/d3.v3.min.js"></script>
		<script src="${rc.contextPath}/assets/js/wsh.js"></script>
		<script type="text/javascript">
			var message = "${message}";
			if(!isEmpty(message)) {
				showMsg(message);
			}
		</script>
		<script src="${rc.contextPath}/assets/js/moment.min.js"></script>
		<script src="${rc.contextPath}/assets/js/bootstrap-datetimepicker.min.js"></script>

		<!-- inline scripts related to this page -->
<script type="text/javascript">
jQuery(function($) {
	StartTree();//开始加载树
})
//定义
var margin = {top: 20, right: 120, bottom: 20, left: 120},
     width = 2000 - margin.right - margin.left,
     height = 800 - margin.top - margin.bottom;
     
var i = 0,duration = 750,root;
d3.rgb("decimal");//取色，白色#000000
var tree = d3.layout.tree().size([height, width]);

var diagonal = d3.svg.diagonal().projection(function(d) { return [d.y, d.x]; });

var svg = d3.select("div").append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom)
  	.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");//transform移动指定位置

d3.select(self.frameElement).style("height", "800px");
    
function StartTree(){
	d3.json("${rc.contextPath}/message/QueryTreeStructure?rootNodeId=1", function(error, flare) {
		if (error) {
			alert("加载树出现异常");
			throw error;
		}
		root = flare;
		root.x0 = height / 2;
		root.y0 = 0;
	
		function collapse(d) {
	    	if (d.children) {
	    		d._children = d.children;
	      		d._children.forEach(collapse);
	      		d.children = null;
	    	}
		}
		//下面一行代码是：全部的树节点都展开
		//root.children.forEach(collapse);
		update(root);
	});
}

function update(source) {
	// Compute the new tree layout.
   	var nodes = tree.nodes(root).reverse();//计算并返回  指定结点(source)   的子结点信息.:此行的结果是nodes数组：0-9：由下往上直到根节点漏斗
    var links = tree.links(nodes);//连接线包含：source和target
    
   	// Normalize for fixed-depth.规范化节点深度
   	nodes.forEach(function(d) { d.y = d.depth * 180; });
   	
   	// Update the nodes…
   	var node = svg.selectAll("g.node")
       .data(nodes, function(d) { return d.id || (d.id = ++i); });
   	
   	// Enter any new nodes at the parent's previous position.//数组多余Dom元素，enter提取出来
   	var nodeEnter = node.enter().append("g")
    	.attr("class", "node")
       	.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; });
       	

   	nodeEnter.append("circle")
    	.attr("r", 1e-6)
       	.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; }).on("click", click);
   	
   	nodeEnter.append("text")
       	.attr("x", function(d) { return d.children || d._children ? -10 : 10; })
       	.attr("dy", ".35em")
       	.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
//      .attr("text-anchor", function(d) {if(d.nodeId != "root"){return d.children || d._children ? "end" : "start"; }else{return "end";}})
       	.text(function(d) { return d.nodeName; })
       	.style("fill-opacity", 1e-6)
       	.on("click", clickEdit);

   	// Transition nodes to their new position.//过度节点到他们的新位置，并选中circle和text，为其修改样式
   	var nodeUpdate = node.transition()
       	.duration(duration)
       	.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });

   	nodeUpdate.select("circle")
       	.attr("r", 4.5)
       	.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
   	
   	nodeUpdate.select("text")
       	.style("fill-opacity", 1);

   	// Transition exiting nodes to the parent's new position.
   	var nodeExit = node.exit().transition()
       	.duration(duration)
       	.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
       	.remove();

   	nodeExit.select("circle")
       	.attr("r", 1e-6);

   	nodeExit.select("text")
       	.style("fill-opacity", 1e-6);

   	// Update the links…
   	var link = svg.selectAll("path.link")
       	.data(links, function(d) { return d.target.id; });

   	// Enter any new links at the parent's previous position.//在选定的g前增加元素path
   	link.enter().insert("path", "g")
       	.attr("class", "link")
       	.attr("d", function(d) {
        	var o = {x: source.x0, y: source.y0};
         	return diagonal({source: o, target: o});
       	});

   	// Transition links to their new position.
   	link.transition()
       	.duration(duration)
       	.attr("d", diagonal);

   	// Transition exiting nodes to the parent's new position.
   	link.exit().transition()
       	.duration(duration)
       	.attr("d", function(d) {
         	var o = {x: source.x, y: source.y};
         	return diagonal({source: o, target: o});
       	})
       	.remove();

   	// Stash the old positions for transition.
   	nodes.forEach(function(d) {
     	d.x0 = d.x;
     	d.y0 = d.y;
   	});
}

// Toggle children on click.
function click(d) {
   	if (d.children) {//缩小时调用
     	d._children = d.children;
     	d.children = null;
   	} else {//点击扩大时调用
		d.children = d._children;
 		d._children = null;
 	}
   	update(d);
}

function clickEdit(d){
	//查询数据库得到此d节点下，可以允许增加的节点
	$.ajax({
			url: "${rc.contextPath}/message/isAddNodeList?nodeId="+d.nodeId,
 		   	dataType:"json",
 		   	success: function(dataList){
 		   		console.log("data......"+dataList.length);
		   		console.log(dataList);
				$(window).ShowDialog({
					nodeId: d.nodeId,
					width: 800, 
			        height: 400, 
			        title: "选择可以增加的节点",
			        data: dataList
			    });
 		   	}
 	});
}
var Dialog = {
	    RemoveDialog: function() {
	        $("#dFilter").remove();
	        $("#dBody").remove();
	        Dialog.ShowSelect();
	    }
	}
	$(function() {
	    $.fn.extend({
	        ShowDialog: function(options) {
	            //插件内部函数
	            var nFun = {
	                HideSelect: function() {
	                    $("select").hide();
	                },
	                ShowSelect: function() {
	                    $("select").show();
	                },
	                RemoveDialog: function() {
	                    $("#dFilter").remove();
	                    $("#dBody").remove();
	                    nFun.ShowSelect();
	                },
	                CenterShow: function(dBody, width, height) {
	                    var topPX = 0;
	                    topPX = $(document.documentElement).height() - height;
	                    if (topPX < 0) {
	                        topPX = 0;
	                    } else {
	                        topPX = $(document.documentElement).scrollTop() + topPX / 2;
	                    }
	                    var leftX = $(document.documentElement).width() - width;
	                    if (leftX < 0) {
	                        leftX = 0;
	                    } else {
	                        leftX = $(document.documentElement).scrollLeft() + leftX / 2;
	                    }
	                    dBody.css({ "left": leftX + "px", "top": topPX + "px" });
	                }
	            }
	            var settings = {
	                height: 400, //弹出框的高度
	                width: 400, //弹出框的宽度
	                title: "标题", // 弹出框的标题
	                src: "", //弹出框的页面URL
	                data: "",
	                nodeId: "",
	                beforeShow: nFun.HideSelect, //在显示弹出框之前的方法
	                afterClose: nFun.ShowSelect //在关闭弹出框之后的方法
	            };
	            if (options) {//合并值
	                $.extend(settings, options);
	            }
	            nFun.RemoveDialog();
	            settings.beforeShow();
	            //背影遮盖(是否为模式窗口)
	            var dFilter = $('<div id="dFilter" class="dFilter"></div>').appendTo(document.body);
	            dFilter.css("opacity", "0.5");
	            dFilter.css("height", $(document).height());
	            dFilter.css("width", $(document).width());
	            
	            //弹出页面的主DIV
	            var dBody = $('<div id="dBody" class="dBody"  ></div>').appendTo(document.body);
	            var dBodyHeight = settings.height + 20;
	            dBody.css({ "width": settings.width + "px", "height": dBodyHeight + "px" });
	            
	            //弹出页面的头部
	            var dHeader = $('<div class="dHeader" ></div>').appendTo(dBody);
	            //弹出页面的标题
	            var dTitle = $('<label id="'+i+'" value="'+i+'" onClick="aaa(this.value)"></label>').appendTo(dHeader);
	            dTitle.text(settings.title);
	            //弹出页面的关闭按钮
	            var dClose = $('<img alt="" />').appendTo(dHeader);
	            
	            
	            //弹出页面的可增加选项
	            var dHeaderEdit = $('<div class="dHeaderEdit" ></div>').appendTo(dBody);
	            for (var i=0;i<settings.data.length;i++){
	            	var dTitleEdit = $('<select id="'+i+'" onChange="selectValueEdit(this.value)"></select>').appendTo(dHeaderEdit);
	            	var dd = settings.data[i];
	            	if(dd.Channel != undefined){
	            		for (var k=0;k<dd.Channel.length;k++){
			            	dTitleEdit.append("<option value='"+dd.Channel[k].id+","+dd.Channel[k].name+"'>"+dd.Channel[k].name+"</option>");
						}
	            	}
	            	if(dd.Device != undefined){
	            	for (var k=0;k<dd.Device.length;k++){
		            	dTitleEdit.append("<option value='"+dd.Device[k].id+","+dd.Device[k].name+"'>"+dd.Device[k].name+"</option>");
					}}
	            	if(dd.Page != undefined){
	            	for (var k=0;k<dd.Page.length;k++){
	            		//dTitleEdit.text(settings.title);
		            	dTitleEdit.append("<option value='"+dd.Page[k].id+","+dd.Page[k].name+"'>"+dd.Page[k].name+"</option>");
					}}
				}
				var dInput = $('<input id="treeNodeEdit" value="" disabled="disabled"></input>').appendTo(dHeaderEdit);
				var dHidden = $('<hidden id="treeNodeEditValue" value="" disabled="disabled"></hidden>').appendTo(dHeaderEdit);
				var dButton = $('<button id="treeNodeEditButton" >确定</button>').appendTo(dHeaderEdit);
				for (var i=0;i<settings.data.length;i++){
	            	var dd = settings.data[i];
	            	if(dd.Channel != undefined){
	            		for (var k=0;k<dd.Channel.length;k++){
	            			document.getElementById("treeNodeEditValue").value=dd.Channel[k].id;
	            			document.getElementById("treeNodeEdit").value=dd.Channel[k].name;break;
						}
	            	}
	            	if(dd.Device != undefined){
	            	for (var k=0;k<dd.Device.length;k++){
	            		document.getElementById("treeNodeEditValue").value=dd.Device[k].id;
            			document.getElementById("treeNodeEdit").value=dd.Device[k].name;break;
					}}
	            	if(dd.Page != undefined){
	            	for (var k=0;k<dd.Page.length;k++){
	            		document.getElementById("treeNodeEditValue").value=dd.Page[k].id;
            			document.getElementById("treeNodeEdit").value=dd.Page[k].name;break;
					}}
				}
				
				
				var dHeader2 = $('<div class="dHeader" ></div>').appendTo(dBody);
	            //弹出页面的标题
	            var dTitle2 = $('<label id="'+i+'" value="'+i+'" "></label>').appendTo(dHeader2);
	            dTitle2.text("删除此节点？");
	            //弹出页面的关闭按钮
	            //var dClose2 = $('<img alt="" />').appendTo(dHeader);
				
				
	            //删除此节点提示
	            var dHeaderDelete = $('<div class="dHeaderDel" ></div>').appendTo(dBody);
	            //弹出页面的标题
	            var dButtonDelete = $('<button id="treeNodeEdit">删除</button>').appendTo(dHeaderDelete);
	            
	            dButton.click(function(){
					var value = document.getElementById("treeNodeEditValue").value;
					nFun.RemoveDialog();
	              	settings.afterClose();
	              	EditTreeNode(settings.nodeId,value,"add");
				});
	            
	            dButtonDelete.click(function(){
					nFun.RemoveDialog();
	              	settings.afterClose();
	              	DeleteTreeNode(settings.nodeId,"del");
				});
	            
	            //弹出页面的内容容器iframe
	            var dIframe = $('<iframe frameborder="0"  ></iframe>');//.appendTo(dBody);
	            
	            //设置弹出框的宽高
	            var dIframeWidth = settings.width;
	            dIframe.attr({ "width": dIframeWidth + "px", "height": settings.height + "px", "src": settings.src });
	            
	            //设置弹出框居中显示
	            nFun.CenterShow(dBody, settings.width, settings.height);
	            //关闭按钮事件
	            dClose.click(function() {
	                nFun.RemoveDialog();
	                settings.afterClose();
	            });
	            $(window).resize(function() {
	                nFun.CenterShow(dBody, settings.width, settings.height);
	            });
	        }
	    });
	});

function selectValueEdit(value){
	document.getElementById("treeNodeEditValue").value = value.split(",")[0];
	document.getElementById("treeNodeEdit").value = value.split(",")[1];
}

function EditTreeNode(nodeValue,value,type){
	//根据传过来的标志，及节点值，程序执行节点增加操作
	$.ajax({
		   	async:false,
		   	url: "${rc.contextPath}/message/AddOrDelNode?parentNodeId="+nodeValue+"&codeId="+value+"&type="+type,
		   	success: function(data){
		   		StartTree();
		   	},
		    error: function(XMLHttpRequest, textStatus, errorThrown) {
		    	alert(errorThrown);
		    }
 	});
}

function DeleteTreeNode(nodeIdValue,type){
	//根节点不能删除
	if(nodeIdValue == 'root'){
		alert("根节点不能删除");
		return;
	}
	$.ajax({
	   		async:false,
	   		url: "${rc.contextPath}/message/AddOrDelNode?parentNodeId="+nodeIdValue+"&codeId=&type="+type,
	   		//dataType:"json",
	   		success: function(data,tt,msg){
	   			StartTree();
	   		},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert(errorThrown);
		    }
	});
}
</script>
</body>
</html>